using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AddPrefabToGameObject : Singleton<AddPrefabToGameObject>
{
    /// <summary>
    /// 向指定物体添加物体
    /// </summary>
    /// <param name="prefab">预制体引用</param>
    /// <param name="targetObject">指定的物体引用</param>
    public void AddPrefab(GameObject prefab, GameObject targetObject)
    {
        // 确保预制体和目标物体已经被赋值
        if (prefab != null && targetObject != null)
        {
            // 实例化预制体
            GameObject instantiatedPrefab = MonoBehaviour.Instantiate(prefab, Vector3.zero, Quaternion.identity);

            // 将实例的位置设置为目标物体的位置
            instantiatedPrefab.transform.position = targetObject.transform.position;

            // 将实例的父对象设置为目标物体
            instantiatedPrefab.transform.SetParent(targetObject.transform);

            // 可选：根据需要调整实例的局部位置和旋转
            // instantiatedPrefab.transform.localPosition = new Vector3(x, y, z);
            // instantiatedPrefab.transform.localRotation = Quaternion.Euler(pitch, yaw, roll);
        }
        else
        {
            Debug.LogError("预制体或者目标物体不存在");
        }
    }
    
    /// <summary>
    /// 移除所有子对象
    /// </summary>
    /// <param name="target">目标物体</param>
    public void RemoveAllChildObjects(GameObject target)
    {
        Transform transform = target.transform;
        foreach (Transform child in transform)
        {
            MonoBehaviour.Destroy(child.gameObject);
        }
    }

    /// <summary>
    /// 移除指定的子对象
    /// </summary>
    /// <param name="childObject">子物体</param>
    /// <param name="target">目标物体</param>
    public void RemoveChildObject(GameObject childObject, GameObject target)
    {
        Transform transform = target.transform;
        if (childObject != null && childObject.transform.parent == transform)
        {
            MonoBehaviour.Destroy(childObject);
        }
    }
}
